from src.util.Route import *
from src.service import SignService


# from util.Cache import cache


@Get("/test/<username>")
def test(username):
    # print(SignService.test(request.args.get('key')))
    # print(username)
    # te = dict()
    # print(te.get('username') or 'xxl')
    return getUsername()


@route("/captcha")
def captcha():
    r = SignService.getCaptcha(60)
    return R.success(data=r)


@route("/sign/in", methods=['POST'])
def login():
    req = request.json
    try:
        # 人机验证
        r = SignService.authCaptcha(req.get('token'), req.get('code'), True)
        if r is None:
            return R.bad_request("验证码已过期")
        elif not r:
            return R.bad_request("验证码错误")
        # 登陆
        r = SignService.signIn(req['username'], req['password'])
        if r == 0:
            return R.unauthorized("账号或密码错误")
        elif r == 1:
            return R.unauthorized("账号已被锁定")
        return R.success(r, "成功")
    except Exception as e:
        raise e


@route("/sign/up", methods=["POST"])
def signUp():
    req: dict = request.json
    r = SignService.authCaptcha(req['token'], req['code'])
    if r is None:
        return R.bad_request("验证码已过期")
    elif not r:
        return R.bad_request("验证码错误")
    req.pop('code')
    req.pop('token')
    r = SignService.signUp(req)
    if r == 0:
        return R.create(400, msg="用户已存在请重新输入用户名")
    elif r == 3:
        return R.bad_request('注册接口尚未开放')
    return R.success(msg='注册成功')


@route("/sign/has/user")
def hasUser():
    user = request.args.get("username")
    hs = SignService.hasUser(user)
    return R.create(200, hs)


# 用户选择角色登陆登陆
@route("/sign/role")
def roleLogin():
    uid = getUid()
    rid = request.args.get("rid")
    if not rid:
        return R.bad_request("缺少參數")
    r = SignService.roleSignIn(uid, int(rid))
    if r:
        return R.success(r)
    return R.bad_request('登陆失败')
